<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="组织名称" prop="deptName">
          <el-input v-model="queryParams.deptName" placeholder="请输入组织名称" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="组织状态" clearable>
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap paddingAll20" :model="queryParams" ref="queryForm" label-width="86px">
      <div class="table-title-wrap justify-end">

        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:dept:add']">新增
        </el-button>

        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠
        </el-button>

        <!--            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      </div>
      <el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="deptId"
                :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="组织名称" width="260"></el-table-column>
        <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 'edit')"
                       v-hasPermi="['system:dept:edit']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row, 'see')"
                       v-hasPermi="['system:dept:see']">详情
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                       v-hasPermi="['system:dept:add']">新增
            </el-button>
            <el-button v-if="scope.row.parentId != 0" size="mini" type="text" icon="el-icon-delete"
                       @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改组织对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位类型" prop="deptType">
              <el-radio-group v-model="form.deptType" @change="changeDeptType" :disabled="status">
                <el-radio v-for="dict in dict.type.dept_type" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.deptType == 2">
          <el-col :span="12">
            <el-form-item label="所属区域" prop="areaId">
              <el-select v-model="form.areaId" placeholder="请选择所属区域" @change="changeArea"
                         :disabled="status">
                <el-option v-for="areaItem in areaList" :key="areaItem.areaId"
                           :label="areaItem.areaName" :value="areaItem.areaId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在城市" prop="regionId">
              <el-cascader :props="customProps" :options="regionList" v-model="form.regionId"
                            :disabled="status"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级组织" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer"
                          placeholder="选择上级组织" :disabled="status" @select="changeDept"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组织名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入组织名称" :disabled="status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <!--                            <el-input-number v-model="form.orderNum" controls-position="right" @change="value=value.replace(/[^0-9]/g,'')" :min="0" :precision="0"/>-->
              <el-input v-model.number="form.orderNum" type="number" placeholder="请输入内容"
                        oninput="value=value.replace(/[^0-9]/g,'')" :disabled="status"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.deptType == 2">
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" maxlength="20"
                        :disabled="status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入联系电话" maxlength="11"
                        :disabled="status"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.deptType == 1">
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" :disabled="status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" :disabled="status"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" :disabled="status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" maxlength="11" :disabled="status"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.deptType == 2">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" :disabled="status"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" :disabled="status"/>
            </el-form-item>
          </el-col>

          <template v-if="form.deptType == 2">
            <el-col :span="12">
              <el-form-item label="通讯地址" prop="mailingAddress">
                <el-input v-model="form.mailingAddress" placeholder="请输入通讯地址" maxlength="50"
                          :disabled="status"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真" prop="facsimile">
                <el-input v-model="form.facsimile" placeholder="请输入传真" :disabled="status"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="openingBank">
                <el-input v-model="form.openingBank" placeholder="请输入开户行" :disabled="status"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号" prop="account">
                <el-input v-model="form.account" placeholder="请输入账号" :disabled="status"/>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="12">
            <el-form-item label="NC信息" prop="ncName">
              <el-select v-model="form.ncId" filterable placeholder="请选择NC信息" :disabled="status" @change="changeNCId">
                <el-option
                    v-for="(item, index) in ncList"
                    :key="index"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="NCid" prop="ncId">
              <el-input v-model="form.ncId" placeholder="选择NC信息自动带出" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="NC编码" prop="ncCode">
              <el-input v-model="form.ncCode" placeholder="选择NC信息自动带出" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="组织状态">
              <el-radio-group v-model="form.status" :disabled="status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                          :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, areaList, regionList} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SearchContent from "@/components/SearchContent/index.vue";
import * as ncApi from "@/api/system/nc"
import {branchList, deptList} from "@/api/system/nc";
export default {
  name: "Dept",
  dicts: ['sys_normal_disable', 'dept_type'],
  components: {Treeselect, SearchContent},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 组织树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级组织不能为空", trigger: "blur"}
        ],
        areaId: [
          {required: true, message: "请选择所在区域", trigger: "blur"}
        ],
        regionId: [
          {required: true, message: "请选择所在城市", trigger: "blur"}
        ],
        deptName: [
          {required: true, message: "组织名称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "显示排序不能为空", trigger: ["blur", "change"]}
        ],
        creditCode: [
          {required: true, message: "统一社会信用代码不能为空", trigger: "blur"}
        ],
        legalRepresentative: [
          {required: true, message: "法定代表人不能为空", trigger: "blur"}
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      areaList: [],
      customProps: {
        // emitPath: false, // 只返回该节点的值
        value: "regionId", // 自定义要映射的键名
        label: "regionName",
        children: "children",

      },
      regionList: [],
      modalKey: [],
      status: false, // 弹框是否可编辑

      ncList:[],//部门|公司对应的NC列表
      superiorDeptId:null,//当前组织对应的NCid(如果该组织不是公司需向上查找最近的公司NCid)

    };
  },
  created() {
    this.getList();
    this.getAreaList();
  },
  methods: {
    // 单位类型改变
    changeDeptType(val){
        if(val==1){//部门
          this.getDeptNCInfo()
        }else if(val==2){//公司
          this.getCompanyNCInfo()
        }
    },
    //获取NC信息
    changeNCId(id){
      const ncObj= this.ncList.find(item=>item.id==id);
      console.log('nc信息', ncObj)
      this.form.ncCode=ncObj.code;
    },
    //获取公司NC信息
    getCompanyNCInfo(){
      ncApi.branchList().then(res=>{
        this.ncList=res||[];
      })
    },
    //获取部门公司id
    getDeptNCInfo(){
      if(this.superiorDeptId){
        ncApi.deptList({
          superiorDeptId:this.superiorDeptId
        }).then(res=>{
          this.ncList=res||[];
        })
      }
    },
    //部门或者组织发生改变
    changeDept(e){
      if(this.form.deptType==1){//部门
        const deptObj=e;
        if(deptObj.deptType==2){//当选组织是公司
          this.superiorDeptId=deptObj.ncId;
          this.getDeptNCInfo()
        }else {//当前组织是部门->查找部门所属公司的ncId
          const  parentId=deptObj.parentId
          getDept(parentId).then(parentRes=>{
            this.superiorDeptId=parentRes?.data?.ncId;
            this.getDeptNCInfo();
          })
        }
      }
    },

    /** 获取区域列表*/
    getAreaList() {
      areaList().then(res => {
        this.areaList = res.data;
      })
    },
    changeArea(val) {
      this.getReginList(val)
    },
    getReginList(areaId) {
      regionList({
        regionLevel: 2,
        areaId: areaId
      }).then(res => {
        let dataSoures = res.data;
        this.regionList = this.formatRegionList(dataSoures)
        console.log('11111')
      })
    },
    formatRegionList(dataSoures) {
      let parents = dataSoures.filter(item => item.regionLevel === 2)
      let children = dataSoures.filter(item => item.regionLevel > 2)
      let translator = (parents, children) => {
        parents.forEach(item => {
          children.forEach((current, index) => {
            if (current.parentRegionId === item.regionId) {
              let temp = JSON.parse(JSON.stringify(children))
              temp.splice(index, 1)
              translator([current], temp)
              typeof item.children !== 'undefined' ? item.children.push(current) : item.children = [current]
            }
          })
        })
      }
      translator(parents, children)
      return parents
    },
    /** 查询组织列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换组织数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: null,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        deptType: '1',
        area: null,
        regionId: null,
        creditCode: null,
        legalRepresentative: null,
        contacts: null,
        mailingAddress: null,
        facsimile: null,
        openingBank: null,
        account: null,
        ncName:null,//ncName
        ncId:null,
        ncCode:null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.status = false
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
        if(row.deptType==2){
          const parentId=row.deptId;
          getDept(parentId).then(parentRes=>{
            this.superiorDeptId=parentRes?.data?.ncId;
            this.getDeptNCInfo();
          })
        }
      }
      this.open = true;
      this.title = "添加组织";
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });


    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.reset();
      if (type == 'edit') {
        this.status = false
      } else {
        this.status = true
      }
      getDept(row.deptId).then(response => {
        this.form = response.data;
        listDeptExcludeChild(row.deptId).then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
          if (this.deptOptions.length == 0) {
            const noResultsOptions = {deptId: this.form.parentId, deptName: this.form.parentName, children: []};
            this.deptOptions.push(noResultsOptions);
          }
        });
        if (this.form.deptType == 2) {//公司
          this.getReginList(this.form.areaId);
          this.$nextTick(() => {
            this.form.regionId = this.form.regionId.split('/')
          })
          this.getCompanyNCInfo()
        }else {//部门->获取上级公司的NCid
          const parentId=response.data.parentId;
          getDept(parentId).then(parentRes=>{
            this.superiorDeptId=parentRes?.data?.ncId;
            this.getDeptNCInfo();
          })
        }
        this.title = "修改组织";
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm: function () {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptType == 2 && this.form.regionId?.length > 0) {
            this.form.regionId = this.form.regionId.join('/')
          }
          let info = JSON.parse(JSON.stringify(this.form))
          if (info.deptType == 1) {
            this.$delete(info, 'regionId')
          }
          if (this.form.deptId != undefined) {
            updateDept(info).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(info).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function () {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
